/*
 * @Author: asushiye
 * @Date: 2020-07-02 15:30:23
 * @Commit: file content
 */
import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { AfMessageService, AfUpDownService } from '@core';
import { STColumn, STComponent } from '@delon/abc/st';
import { XlsxService } from '@delon/abc/xlsx';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';
import { AfExcelService, ExcelUploadRecord } from 'src/app/routes/system/excel/af-excel.service';
import { ExcelUploadComponent } from 'src/app/routes/system/excel/upload/excel-upload.component';

import { CodeGenService } from '../../codegen.service';

@Component({
  selector: 'app-cg-datatype',
  templateUrl: './cg-datatype.component.html',
  styles: [
    `
      nz-select {
        margin-right: 8px;
        width: 180px;
      }
    `
  ]
})
export class CgDatatypeComponent implements OnInit {
  rows: any[] = [];
  databaseTypes: any[] = [];
  queryParams: any = {
    databaseType: '',
    dataType: ''
  };

  uploadRecord: ExcelUploadRecord = {
    currentQueueId: '',
    business: 'cg-datatype',
    title: '数据类型字典',
    showExtendedFields: false,
    action: 'save',
    sourceId: '1',
    remark: ''
  };

  isLoading = false;

  @ViewChild('st', { static: false }) st!: STComponent;
  columns: STColumn[] = [
    { title: '序号', index: 'ordinalPosition', sort: true },
    { title: '数据库类型', index: 'databaseType', sort: true },
    { title: '通用码', index: 'unifiedCode' },
    { title: '类型名称', index: 'dataTypeName' },
    { title: '数据类型', index: 'dataType' },
    { title: '字节大小', index: 'byteSize' },
    { title: '使用格式', index: 'useFormat' },
    {
      title: '操作',
      buttons: [
        {
          text: '更多',
          children: [
            {
              text: '删除',
              icon: 'delete',
              type: 'del',
              tooltip: `删除此记录`,
              pop: {
                title: '您确定要删除此记录吗？',
                okType: 'danger',
                icon: 'star'
              },
              click: (record, _modal) => {
                this.delete(record);
              }
            },
            {
              text: '查看JSON',
              icon: 'bug',
              click: (record, _modal) => {
                this.viewJson(record);
              }
            }
          ]
        }
      ]
    }
  ];

  constructor(
    private cdr: ChangeDetectorRef,
    private msg: AfMessageService,
    private datatype: CodeGenService,
    private codegen: CodeGenService,
    private modal: ModalHelper,
    private excelSrv: AfExcelService
  ) {}
  ngOnInit() {
    this.queryDatabaseType();
    this.query();
  }

  public queryDatabaseType() {
    this.isLoading = true;
    this.cdr.detectChanges();
    try {
      this.codegen.getDataTypeList().subscribe(body => {
        if (body.status) {
          this.databaseTypes = [];
          this.databaseTypes = body.data;
          console.log(JSON.stringify(this.databaseTypes));
        } else {
          this.msg.notice_warning('查询数据库类型列表', `警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 200);
    }
  }

  public query() {
    this.isLoading = true;
    this.cdr.detectChanges();
    try {
      this.datatype.query(this.queryParams).subscribe(body => {
        if (body.status) {
          this.rows = [];
          this.rows = body.data;
          // console.log(JSON.stringify(this.rows));
        } else {
          this.msg.notice_warning('查询文件', `警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 200);
    }
  }

  importData() {
    this.uploadRecord.currentQueueId = 0;
    const record = this.uploadRecord as any;
    this.modal.create(ExcelUploadComponent, { record }, { size: 'md' }).subscribe(res => {
      if (res.status) {
        this.uploadRecord.currentQueueId = res.data;
        this.query();
      }
    });
  }

  isExporting = false;
  exportData() {
    try {
      this.isExporting = true;
      this.excelSrv.exportData(this.uploadRecord, this.queryParams);
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
        this.isExporting = false;
      }, 1500);
    }
  }

  isLogExporting = false;
  exportLog() {
    try {
      this.isLogExporting = true;
      this.excelSrv.exportLog(this.uploadRecord);
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
        this.isLogExporting = false;
      }, 1500);
    }
  }

  downloadTemplate() {
    this.cdr.detectChanges();
    try {
      this.excelSrv.downTemplateFile(this.uploadRecord);
    } finally {
      this.cdr.detectChanges();
    }
  }

  navUploadLogView() {
    this.excelSrv.navUploadLogView(this.uploadRecord);
  }

  delete(item: any) {
    try {
      this.datatype.delete(item.id).subscribe(body => {
        if (body.status) {
          this.rows = [];
          this.msg.notice_success('删除记录', `${item.fileName} 删除成功`);
          this.query();
        } else {
          this.msg.notice_warning('删除记录', `${item.fileName} 删除失败，警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  // 查看当然记录 -- 用于开发测试
  viewJson(record: any = {}) {
    this.codegen.viewJson(record);
  }
}
